package club.ljwang.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @Auther: wangl
 * @Date: 2020/2/26 21:40
 * @Description:
 */
public class QiniuUtil {

    //构造一个带指定 Region 对象的配置类
    private static Configuration cfg = new Configuration(Region.huadong());
    //...其他参数参考类注释

    private static UploadManager uploadManager = new UploadManager(cfg);
    private static String accessKey = "214_Bs_isx5UNCY1zdSomiFwe94UkL6a4c0a0-GN";
    private static String secretKey = "Fy7AtbO94oCqKvYanyL5G9-RKS7aMMo_MrwGRtMv";
    private static String bucket = "ljwang";


    public static void upload(byte[] data, String key) {

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(data, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (
                QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }


    public static void delete(String key) {


        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

}
